package api

import (
	"fmt"
	"gitee.com/lv-forever/open-ai-api/config"
	"github.com/gin-gonic/gin"
	gogpt "github.com/sashabaranov/go-gpt3"
)

type CompletionsRequestBody struct {
	Prompt string `json:"msg"`
}

type CreateImageRequestBody struct {
	*gogpt.ImageRequest
}

// Complete question
func ASK(c *gin.Context) {
	var requestbody CompletionsRequestBody
	err := c.BindJSON(&requestbody)
	if err != nil {
		c.JSON(400, gin.H{
			"error":  "Invalid request",
			"reason": "",
		})
		return
	}
	message := gogpt.ChatCompletionMessage{
		Role:    "user",
		Content: requestbody.Prompt}

	gptRequestBody := gogpt.ChatCompletionRequest{
		Model:    gogpt.GPT3Dot5Turbo0301,
		Messages: []gogpt.ChatCompletionMessage{message},
	}

	//get Token
	apiKey, err := config.GetAPIKey()
	if err != nil {
		c.JSON(503, gin.H{
			"error":  "Failed to get apiKey!",
			"reason": fmt.Sprintf(err.Error()),
		})
		return
	}

	// create gpt request
	gptClient := gogpt.NewClient(apiKey)
	gptResponse, err := gptClient.CreateChatCompletion(c, gptRequestBody)
	if err != nil {
		c.JSON(503, gin.H{
			"error":  "Failed to get response from OpenAI",
			"reason": fmt.Sprintf(err.Error()),
		})
		return
	}
	c.JSON(200, gin.H{
		"answer": gptResponse.Choices[0].Message.Content,
	})
	return
}

// add OpenAI-Key
func AddAPIKey(c *gin.Context) {
	key := c.Query("key")
	err := config.AddKey(key)
	if err != nil {
		c.JSON(400, gin.H{
			"error":  "Invalid request",
			"reason": fmt.Sprintf(err.Error()),
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "success",
	})
	return
}
